package com.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.config.HadoopConfiguration;
import com.entity.*;
import com.github.pagehelper.Page;
import com.service.*;
import com.util.VeDate;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController // 定义为控制器 返回JSON类型数据
@RequestMapping(value = "/index/", produces = "application/json; charset=utf-8") // 设置请求路径
@CrossOrigin // 允许跨域访问其资源
public class IndexController extends BaseController {

    // @Autowired的作用是自动注入依赖的ServiceBean
    @Autowired
    private AsksService asksService;
    @Autowired
    private SellerService sellerService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CateService cateService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CartService cartService;
    @Autowired
    private HistService histService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private TopicService topicService;
    @Autowired
    private ComplainsService complainsService;
    @Autowired
    private FavService favService;
    @Autowired
    private RecommendService recommendService;
    @Autowired
    private HadoopConfiguration hadoopConfiguration;

    // 预处理 获取基础参数
    @GetMapping(value = "front.action")
    public Map<String, Object> front() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Cate> cateList = this.cateService.getAllCate();
        map.put("cateList", cateList);
        List<Goods> hotList = this.goodsService.getGoodsByHot();

        //视图调用
        //List<Goods> hotList = this.goodsService.getGoodsByHotView();

        map.put("hotList", hotList);
        return map;
    }

    @RequestMapping(value = "query.action")
    public Map<String, Object> query(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "12") Integer limit,
                                     String name) {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<Goods> pager = com.github.pagehelper.PageHelper.startPage(page, limit);// 定义当前页和分页条数
        Goods goods = new Goods();
        goods.setGoodsname(name);
        List<Goods> goodsList = this.goodsService.getGoodsByLike(goods);
        // 返回的map中定义数据格式
        map.put("count", pager.getTotal());
        map.put("total", goodsList.size());
        map.put("data", goodsList);
        map.put("code", 0);
        map.put("msg", "");
        map.put("page", page);
        map.put("limit", limit);
        return map;
    }

    // 前台首页
    @GetMapping(value = "index.action")
    public Map<String, Object> index() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Cate> cateList = this.cateService.getCateFront();
        List<Cate> frontList = new ArrayList<Cate>();
        for (Cate cate : cateList) {
            List<Goods> goodsList = this.goodsService.getGoodsByCate(cate.getCateid());
            cate.setGoodsList(goodsList);
            frontList.add(cate);
        }
        map.put("frontList", frontList);
        return map;
    }

    // 新闻公告
    @GetMapping(value = "article.action")
    public Map<String, Object> article(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer limit) {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<Article> pager = com.github.pagehelper.PageHelper.startPage(page, limit);// 定义当前页和分页条数
        List<Article> list = this.articleService.getAllArticle();
        // 返回的map中定义数据格式
        map.put("count", pager.getTotal());
        map.put("total", list.size());
        map.put("data", list);
        map.put("code", 0);
        map.put("msg", "");
        map.put("page", page);
        map.put("limit", limit);
        return map;
    }

    // 公告详情
    @GetMapping(value = "read.action")
    public Map<String, Object> read(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        Article article = this.articleService.getArticleById(id);
        article.setHits("" + (Integer.parseInt(article.getHits()) + 1));
        this.articleService.updateArticle(article);
        map.put("article", article);
        return map;
    }

    // 用户登录
    @PostMapping(value = "login.action")
    public Map<String, Object> login(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr);
        String username = obj.getString("username");
        String password = obj.getString("password");
        Users usersEntity = new Users();
        usersEntity.setUsername(username);
        List<Users> userslist = this.usersService.getUsersByCond(usersEntity);
        if (userslist.size() == 0) {
            map.put("success", false);
            map.put("message", "用户名不存在");
        } else {
            Users users = userslist.get(0);
            if (password.equals(users.getPassword())) {
                map.put("success", true);
                map.put("message", "登录成功");
                map.put("userid", users.getUsersid());
                map.put("username", users.getUsername());
                map.put("realname", users.getRealname());
            } else {
                map.put("success", false);
                map.put("message", "密码错误");
            }
        }
        return map;
    }

    @PostMapping(value = "slogin.action")
    public Map<String, Object> slogin(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr);
        String username = obj.getString("username");
        String password = obj.getString("password");
        Seller sellerEntity = new Seller();
        sellerEntity.setUsername(username);
        List<Seller> sellerlist = this.sellerService.getSellerByCond(sellerEntity);
        if (sellerlist.size() == 0) {
            map.put("success", false);
            map.put("message", "商户不存在");
        } else {
            Seller seller = sellerlist.get(0);
            if ("待审核".equals(seller.getStatus())) {
                map.put("success", false);
                map.put("message", "商户待审核");
            } else if (password.equals(seller.getPassword())) {
                map.put("success", true);
                map.put("message", "登录成功");
                map.put("sellerid", seller.getSellerid());
                map.put("username", seller.getUsername());
                map.put("sellername", seller.getSellername());
            } else {
                map.put("success", false);
                map.put("message", "密码错误");
            }
        }
        return map;
    }

    // 忘记密码1
    @PostMapping(value = "forget.action")
    public Map<String, Object> forget(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr);
        String username = obj.getString("username");
        Users usersEntity = new Users();
        usersEntity.setUsername(username);
        List<Users> userslist = this.usersService.getUsersByCond(usersEntity);
        if (userslist.size() == 0) {
            map.put("success", false);
            map.put("message", "用户名不存在");
        } else {
            map.put("success", true);
            map.put("message", "验证成功");
            map.put("users", userslist.get(0));
        }
        return map;
    }

    // 获取提示问题
    @GetMapping(value = "asks.action")
    public List<Asks> asks() {
        return this.asksService.getAllAsks();
    }

    // 用户注册
    @PostMapping(value = "register.action")
    public Map<String, Object> register(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
        Users users = new Users();
        users.setUsername(obj.getString("username"));
        users.setPassword(obj.getString("password"));
        users.setSex(obj.getString("sex"));
        users.setBirthday(obj.getString("birthday"));
        users.setContact(obj.getString("contact"));
        users.setRealname(obj.getString("realname"));
        users.setAsksid(obj.getString("asksid"));
        users.setAnswer(obj.getString("answer"));
        users.setRegdate(VeDate.getStringDateShort());
        int num = this.usersService.insertUsers(users);
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "注册成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "注册失败");
        }
        return map;
    }

    @PostMapping(value = "sregister.action")
    public Map<String, Object> sregister(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
        Seller seller = new Seller();
        seller.setUsername(obj.getString("username")); // 为用户名赋值
        seller.setPassword(obj.getString("password")); // 为密码赋值
        seller.setSellername(obj.getString("sellername")); // 为店铺名称赋值
        seller.setContact(obj.getString("contact")); // 为联系方式赋值
        seller.setAddress(obj.getString("address")); // 为联系地址赋值
        seller.setStatus("待审核"); // 为状态赋值
        seller.setRegdate(VeDate.getStringDateShort()); // 为注册日期赋值
        int num = this.sellerService.insertSeller(seller);
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "注册成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "注册失败");
        }
        return map;
    }

    // 修改密码
    @PostMapping(value = "editpwd.action")
    public Map<String, Object> editpwd(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
        String userid = obj.getString("userid");
        String password = obj.getString("password");
        String repassword = obj.getString("repassword");
        int num = 0;
        Users users = this.usersService.getUsersById(userid);
        if (password.equals(users.getPassword())) {
            users.setPassword(repassword);
            num = this.usersService.updateUsers(users);
            if (num > 0) {
                map.put("success", true);
                map.put("code", num);
                map.put("message", "修改成功");
            } else {
                map.put("success", false);
                map.put("code", num);
                map.put("message", "修改失败");
            }
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "旧密码错误");
        }
        return map;
    }

    @PostMapping(value = "repassword.action")
    public Map<String, Object> repassword(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
        String userid = obj.getString("userid");
        String repassword = obj.getString("repassword");
        System.out.println(jsonStr);
        int num = 0;
        Users users = this.usersService.getUsersById(userid);
        users.setPassword(repassword);
        num = this.usersService.updateUsers(users);
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "修改成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "修改失败");
        }
        return map;
    }

    // 查看个人信息
    @GetMapping(value = "userinfo.action")
    public Map<String, Object> userinfo(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        Users users = this.usersService.getUsersById(id);
        map.put("users", users);
        return map;
    }

    // 修改个人信息
    @PostMapping(value = "personal.action")
    public Map<String, Object> personal(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
        Users users = this.usersService.getUsersById(obj.getString("usersid"));
        users.setUsername(obj.getString("username"));
        users.setSex(obj.getString("sex"));
        users.setBirthday(obj.getString("birthday"));
        users.setContact(obj.getString("contact"));
        users.setRealname(obj.getString("realname"));
        int num = this.usersService.updateUsers(users);
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "修改成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "修改失败");
        }
        return map;
    }

    // 查看购物车
    @GetMapping(value = "cart.action")
    public Map<String, Object> cart(String userid) {
        Map<String, Object> map = new HashMap<String, Object>();
        Cart cart = new Cart();
        cart.setUsersid(userid);
        List<Cart> cartList = this.cartService.getCartByCond(cart);
        map.put("cartList", cartList);
        map.put("num", cartList.size());
        return map;
    }

    // 删除购物车中的商品
    @RequestMapping(value = "deletecart.action")
    public Map<String, Object> deletecart(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        int num = this.cartService.deleteCart(id);
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "删除成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "删除失败");
        }
        return map;
    }

    // 查看订单
    @RequestMapping(value = "showOrders.action")
    public Map<String, Object> showOrders(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit,
                                          String userid) {
        Map<String, Object> map = new HashMap<String, Object>();
        Orders orders = new Orders();
        orders.setUsersid(userid);
        Page<Orders> pager = com.github.pagehelper.PageHelper.startPage(page, limit);// 定义当前页和分页条数
        List<Orders> list = this.ordersService.getOrdersByCond(orders);
        // 返回的map中定义数据格式
        map.put("count", pager.getTotal());
        map.put("total", list.size());
        map.put("data", list);
        map.put("code", 0);
        map.put("msg", "");
        map.put("page", page);
        map.put("limit", limit);
        return map;
    }

    // 添加商品到购物车
    @PostMapping(value = "addcart.action")
    public Map<String, Object> addcart(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
        Cart cart = new Cart();
        cart.setUsersid(obj.getString("userid"));
        cart.setAddtime(VeDate.getStringDateShort());
        cart.setGoodsid(obj.getString("goodsid"));
        cart.setNum(obj.getString("num"));
        cart.setPrice(obj.getString("price"));
        int num = this.cartService.insertCart(cart);
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "失败");
        }
        return map;
    }

    // 购物结算
    @RequestMapping(value = "checkout.action", method = RequestMethod.POST)
    public Map<String, Object> checkout(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
        Cart cart1 = new Cart();
        cart1.setUsersid(obj.getString("userid"));
        List<Cart> cartList = this.cartService.getCartByCond(cart1);
        int num = 0;
        if (cartList.size() == 0) {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "失败");
        } else {
            double total = 0;
            for (Cart cart : cartList) {
                // 获取一个1000-9999的随机数 防止同时提交
                String ordercode = "PD" + VeDate.getStringDatex();
                Orders orders = new Orders();
                orders.setAddress(obj.getString("address"));
                orders.setAddtime(VeDate.getStringDateShort());
                orders.setContact(obj.getString("contact"));
                orders.setOrdercode(ordercode);
                orders.setReceiver(obj.getString("receiver"));
                orders.setStatus("未付款");
                orders.setTotal("" + VeDate.getDouble(total));
                orders.setUsersid(obj.getString("userid"));
                orders.setGoodsid(cart.getGoodsid());
                orders.setPrice(cart.getPrice());
                orders.setNum(cart.getNum());
                orders.setTotal(""
                        + VeDate.getDouble(Double.parseDouble("" + Double.parseDouble(cart.getNum()) * Double.parseDouble(cart.getPrice()))));
                num += this.ordersService.insertOrders(orders);
                Goods goods = this.goodsService.getGoodsById(cart.getGoodsid());
                goods.setSellnum("" + (Integer.parseInt(goods.getSellnum()) + Integer.parseInt(cart.getNum())));
                this.goodsService.updateGoods(goods);
                total += Double.parseDouble(cart.getPrice()) * Double.parseDouble(cart.getNum());
                this.cartService.deleteCart(cart.getCartid());
            }
        }
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "失败");
        }
        return map;
    }

    // 确认收货
    @RequestMapping(value = "over.action")
    public Map<String, Object> over(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        Orders orders = this.ordersService.getOrdersById(id);
        orders.setStatus("已收货");
        int num = this.ordersService.updateOrders(orders);
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "收货成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "收货失败");
        }
        return map;
    }

    //作者联系 QQ 1420527913   毕设成品下载网址  codebag.cn
    @RequestMapping(value = "prePay.action")
    public Map<String, Object> prePay(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        Orders orders = this.ordersService.getOrdersById(id);
        map.put("orders", orders);
        return map;
    }

    // 付款
    @RequestMapping(value = "pay.action")
    public Map<String, Object> pay(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        Orders orders = this.ordersService.getOrdersById(id);
        orders.setStatus("已付款");
        int num = this.ordersService.updateOrders(orders);
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "付款成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "付款失败");
        }
        return map;
    }

    // 取消订单
    @RequestMapping(value = "cancel.action")
    public Map<String, Object> cancel(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        Orders orders = this.ordersService.getOrdersById(id);
        orders.setStatus("已取消");
        int num = this.ordersService.updateOrders(orders);
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "取消成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "取消失败");
        }
        return map;
    }

    // 添加意见反馈信息
    @PostMapping(value = "addComplains.action")
    public Map<String, Object> addComplains(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
        Complains complains = new Complains();
        complains.setAddtime(VeDate.getStringDateShort());
        complains.setStatus("未回复");
        complains.setReps(" ");
        complains.setTitle(obj.getString("title"));
        complains.setContents(obj.getString("contents"));
        complains.setUsersid(obj.getString("usersid"));
        int num = this.complainsService.insertComplains(complains);
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "反馈成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "反馈失败");
        }
        return map;
    }

    // 我的意见反馈信息
    @RequestMapping(value = "myComplains.action")
    public Map<String, Object> myComplains(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "12") Integer limit,
                                           String userid) {
        Map<String, Object> map = new HashMap<String, Object>();
        Complains complains = new Complains();
        complains.setUsersid(userid);
        // 定义当前页和分页条数
        Page<Complains> pager = com.github.pagehelper.PageHelper.startPage(page, limit);
        List<Complains> complainsList = this.complainsService.getComplainsByCond(complains);
        // 返回的map中定义数据格式
        map.put("count", pager.getTotal());
        map.put("total", complainsList.size());
        map.put("data", complainsList);
        map.put("code", 0);
        map.put("msg", "");
        map.put("page", page);
        map.put("limit", limit);
        return map;
    }

    @RequestMapping(value = "cate.action")
    public Map<String, Object> cate(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "12") Integer limit,
                                    String id) {
        System.out.println("cateid  ==>  " + id);
        Map<String, Object> map = new HashMap<String, Object>();
        Cate cate = this.cateService.getCateById(id);
        Goods goods = new Goods();
        goods.setCateid(id);
        Page<Goods> pager = com.github.pagehelper.PageHelper.startPage(page, limit);// 定义当前页和分页条数
        List<Goods> goodsList = this.goodsService.getGoodsByCond(goods);
        // 返回的map中定义数据格式
        map.put("count", pager.getTotal());
        map.put("total", goodsList.size());
        map.put("data", goodsList);
        map.put("code", 0);
        map.put("msg", "");
        map.put("page", page);
        map.put("limit", limit);
        map.put("cate", cate);
        return map;
    }

    @RequestMapping(value = "all.action")
    public Map<String, Object> all(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "12") Integer limit) {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<Goods> pager = com.github.pagehelper.PageHelper.startPage(page, limit);// 定义当前页和分页条数
        List<Goods> goodsList = this.goodsService.getAllGoods();
        // 返回的map中定义数据格式
        map.put("count", pager.getTotal());
        map.put("total", goodsList.size());
        map.put("data", goodsList);
        map.put("code", 0);
        map.put("msg", "");
        map.put("page", page);
        map.put("limit", limit);
        return map;
    }

    //给用户推荐商品
    @RequestMapping(value = "recommend.action")
    public List<Goods> recommend(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "12") Integer limit,
                                 String userid) {
		/*Hist hist = new Hist();
		hist.setUsersid(userid);
		List<Hist> histList = this.histService.getHistByCond(hist);
		if (histList.size() == 0) {
			return this.goodsService.getGoodsRecommend();
		} else {
			return this.recommendService.getRecommend(userid);
		}*/

        List<Goods> lstRecommendGoods = new ArrayList<>();
        List<String> lstGoodsId = new ArrayList<>();
        int nIndex = 0;


        if (null == userid || "".equals(userid) || "null".equals(userid)) {
            //用户为未登录, 根据商品访问记录次数倒序排
            List<Goods> lstAllGoods = this.goodsService.getGoodsRecommend();
            //评价商品   根据积分倒序排
            List<Goods> lstTopicGoods = this.goodsService.getTopicRecommend();

            int nTotal = lstAllGoods.size();

            while (true) {
                if (nIndex >= nTotal) {
                    break;
                }

                if (nIndex < lstAllGoods.size()) {
                    if (!lstGoodsId.contains(lstAllGoods.get(nIndex).getGoodsid())) {
                        lstRecommendGoods.add(lstAllGoods.get(nIndex));
                        lstGoodsId.add(lstAllGoods.get(nIndex).getGoodsid());
                    }
                }

                if (nIndex < lstTopicGoods.size()) {
                    if (!lstGoodsId.contains(lstTopicGoods.get(nIndex).getGoodsid())) {
                        lstRecommendGoods.add(lstTopicGoods.get(nIndex));
                        lstGoodsId.add(lstTopicGoods.get(nIndex).getGoodsid());
                    }
                }

                nIndex++;

                //只保留12个元素
                if (lstRecommendGoods.size() == 12) {
                    break;
                }
            }

        } else {
            //所有商品   访问次数倒序排
            List<Goods> lstAllGoods = this.goodsService.getGoodsRecommend();
            //当前用户   根据大数据推荐的数据进行展示
            List<Goods> lstHadoopGoods = this.goodsService.getHadoopRecommend(userid);
            //评价商品   根据积分倒序排
            List<Goods> lstTopicGoods = this.goodsService.getTopicRecommend();


            int nTotal = lstAllGoods.size();

            while (true) {
                if (nIndex >= nTotal) {
                    break;
                }

                if (nIndex < lstHadoopGoods.size()) {
                    if (!lstGoodsId.contains(lstHadoopGoods.get(nIndex).getGoodsid())) {
                        lstRecommendGoods.add(lstHadoopGoods.get(nIndex));
                        lstGoodsId.add(lstHadoopGoods.get(nIndex).getGoodsid());
                    }
                }

                if (nIndex < lstTopicGoods.size()) {
                    if (!lstGoodsId.contains(lstTopicGoods.get(nIndex).getGoodsid())) {
                        lstRecommendGoods.add(lstTopicGoods.get(nIndex));
                        lstGoodsId.add(lstTopicGoods.get(nIndex).getGoodsid());
                    }
                }

                if (nIndex < lstAllGoods.size()) {
                    if (!lstGoodsId.contains(lstAllGoods.get(nIndex).getGoodsid())) {
                        lstRecommendGoods.add(lstAllGoods.get(nIndex));
                        lstGoodsId.add(lstAllGoods.get(nIndex).getGoodsid());
                    }
                }

                nIndex++;

                //只保留12个元素
                if (lstRecommendGoods.size() == 12) {
                    break;
                }
            }
        }

        return lstRecommendGoods;
    }

    @RequestMapping(value = "detail.action")
    public Map<String, Object> detail(String id) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        Goods goods = this.goodsService.getGoodsById(id);
        goods.setHits("" + (Integer.parseInt(goods.getHits()) + 1));
        this.goodsService.updateGoods(goods);
        map.put("goods", goods);
        Topic topic = new Topic();
        topic.setGoodsid(id);
        List<Topic> topicList = this.topicService.getTopicByCond(topic);
        map.put("topicList", topicList);

        DayVisitRecord dayVisitRecord = new DayVisitRecord("00000000", "游客", goods.getGoodsid(), goods.getGoodsname(), VeDate.getStringDateShort());
        FileUtils.write(new File(hadoopConfiguration.getHadoopLocal() + "logs\\" + HadoopConfiguration.getDayVisit() + "\\data.txt"), dayVisitRecord.toString(), "utf-8", true);
        return map;
    }

    @RequestMapping(value = "userdetail.action")
    public Map<String, Object> userdetail(String id, String userid) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        Goods goods = this.goodsService.getGoodsById(id);
        goods.setHits("" + (Integer.parseInt(goods.getHits()) + 1));
        this.goodsService.updateGoods(goods);
        map.put("goods", goods);
        Topic topic = new Topic();
        topic.setGoodsid(id);
        List<Topic> topicList = this.topicService.getTopicByCond(topic);
        map.put("topicList", topicList);
        System.out.println(" userid ====> " + userid);


        Users users = usersService.getUsersById(userid);
        UserGoodRecord userGoodRecord = new UserGoodRecord(users.getUsersid(), users.getUsername(), goods.getGoodsid(), goods.getGoodsname(), VeDate.getStringDate());
        FileUtils.write(new File(hadoopConfiguration.getHadoopLocal() + "logs\\" + HadoopConfiguration.getUserGood() + "\\data.txt"), userGoodRecord.toString(), "utf-8", true);

        DayVisitRecord dayVisitRecord = new DayVisitRecord(users.getUsersid(), users.getUsername(), goods.getGoodsid(), goods.getGoodsname(), VeDate.getStringDateShort());
        FileUtils.write(new File(hadoopConfiguration.getHadoopLocal() + "logs\\" + HadoopConfiguration.getDayVisit() + "\\data.txt"), dayVisitRecord.toString(), "utf-8", true);
		/*Hist hist = new Hist();
		hist.setUsersid(userid);
		hist.setGoodsid(id);
		List<Hist> histList = this.histService.getHistByCond(hist);
		if (histList.size() == 0) {
			hist.setNum("1");
			this.histService.insertHist(hist);
		}*/
        return map;
    }

    @RequestMapping(value = "preTopic.action")
    public Map<String, Object> preTopic(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        Orders orders = this.ordersService.getOrdersById(id);
        map.put("orders", orders);
        String ordercode = orders.getOrdercode();
        List<Items> itemsList = new ArrayList<Items>();
        Items items = new Items();
        items.setGoodsid(orders.getGoodsid());
        items.setGoodsname(orders.getGoodsname());
        items.setOrdercode(ordercode);
        itemsList.add(items);
        map.put("detailsList", itemsList);
        return map;
    }

    @PostMapping(value = "addTopic.action")
    public Map<String, Object> addTopic(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
        Orders orders = this.ordersService.getOrdersById(obj.getString("ordersid"));
        orders.setStatus("已评价");
        this.ordersService.updateOrders(orders);
        JSONArray detailsList = JSONArray.parseArray(obj.getString("detailsList"));
        int num = 0;
        for (int i = 0; i < detailsList.size(); i++) {
            JSONObject myJson = JSONObject.parseObject(detailsList.getString(i));
            Topic topic = new Topic();
            topic.setAddtime(VeDate.getStringDate());
            topic.setContents(myJson.getString("contents"));
            topic.setGoodsid(myJson.getString("goodsid"));
            topic.setNum(myJson.getString("tnum"));
            topic.setOrdersid(orders.getOrdersid());
            topic.setUsersid(orders.getUsersid());
            topic.setTopicid("T" + VeDate.getStringId() + i);
            num += this.topicService.insertTopic(topic);
        }
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "保存成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "保存失败");
        }
        return map;
    }

    // 加入收藏
    @PostMapping(value = "addfav.action")
    public Map<String, Object> addFav(@RequestBody String jsonStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject obj = JSONObject.parseObject(jsonStr); // 将JSON字符串转换成object
        int num = 0;
        Fav fav = new Fav();
        fav.setUsersid(obj.getString("userid"));
        fav.setGoodsid(obj.getString("goodsid"));
        List<Fav> list = this.favService.getFavByCond(fav);
        if (list.size() != 0) {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "您已经收藏本商品");
            return map;
        }
        fav.setAddtime(VeDate.getStringDateShort());
        num = this.favService.insertFav(fav);
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "收藏成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "收藏失败");
        }
        return map;
    }

    // 我的收藏
    @GetMapping(value = "myfav.action")
    public Map<String, Object> myfav(String userid, @RequestParam(defaultValue = "1") Integer page,
                                     @RequestParam(defaultValue = "10") Integer limit) {
        Map<String, Object> map = new HashMap<String, Object>();
        Page<Fav> pager = com.github.pagehelper.PageHelper.startPage(page, limit);// 定义当前页和分页条数
        Fav fav = new Fav();
        fav.setUsersid(userid);
        List<Fav> list = this.favService.getFavByCond(fav);
        // 返回的map中定义数据格式
        map.put("count", pager.getTotal());
        map.put("total", list.size());
        map.put("data", list);
        map.put("code", 0);
        map.put("msg", "");
        map.put("page", page);
        map.put("limit", limit);
        return map;
    }

    // 删除收藏
    @RequestMapping(value = "deleteFav.action")
    public Map<String, Object> deleteFav(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        int num = this.favService.deleteFav(id);
        if (num > 0) {
            map.put("success", true);
            map.put("code", num);
            map.put("message", "删除成功");
        } else {
            map.put("success", false);
            map.put("code", num);
            map.put("message", "删除失败");
        }
        return map;
    }

    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/*", method = RequestMethod.OPTIONS)
    public ResponseEntity handleOptions() {
        return (ResponseEntity) ResponseEntity.noContent();
    }

    // TODO Auto-generated method stub
}
